/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.generics.client.components.mask;

import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;

/**
 *
 * @author v
 */
public class MaskEditHandler extends Composite {

    private final TextBox textBox = new TextBox();

    public MaskEditHandler() {
        initWidget(textBox);
    }

    @Override
    protected void onAttach() {
        super.onAttach();
        createMaskPhone();
        textBox.setMaxLength(8);
    }

    public HandlerRegistration addBlurHandler(BlurHandler handler) {
        return textBox.addBlurHandler(handler);
    }

    public String getValue() {
        String value = "";
        if (textBox.getValue() != null) {
            value = textBox.getValue().replace("-", "").replace(".", "").replace("/", "");
        }
        return value;
    }

    public String getFormattedValue() {
        return textBox.getValue();
    }

    public String getValueFormated() {
        return textBox.getValue();
    }

    public void setValue(String value) {
        textBox.setValue(value);
        formater();
    }

    private native String formater() /*-{
     $wnd.jQuery(function($){
     $(".decimal").maskMoney('mask');
     });
     }-*/;

    public native Object getValueUnmasked() /*-{
     var num;
     $wnd.jQuery(function($){
     num = $('.decimal').maskMoney('unmasked')[0];
     });
     return String(num);
     }-*/;

    public void setReadOnly(boolean isReadOnly) {
        textBox.setReadOnly(isReadOnly);
    }

    public void setEnabled(boolean enabled) {
        textBox.setEnabled(enabled);
    }
    
    public void setIdField(String id) {
        textBox.getElement().setId(id);
        createMaskPhone();
    }

    private native void createMaskPhone()/*-{
     $wnd.jQuery(function($){
     $("#phone").mask("(99) 9999-9999");
     $("#cpf").mask("999.999.999-99?9-99");
     $("#tin").mask("99-9999999");
     $("#ssn").mask("999-99-9999");
     $(".decimal").maskMoney();
     $("#decimal").maskMoney();
     $("#onlyNumber").mask("99999");
     $("#cnpj").mask("99.999.999/999?9-99");
     });
     }-*/;

}
